<template>
	<div class="login-page">
		<el-card class="login-card" shadow="always" @keyup.enter.native="handleLogin">
			<h2>鸿科碳素涧底过磅称重系统</h2>
			<el-form :model="loginForm" :rules="loginRules" ref="loginFormRef" label-width="100px">
				<el-form-item label="用户名" prop="username">
					<el-input v-model="loginForm.username" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="密码" prop="password">
					<el-input type="password" v-model="loginForm.password" autocomplete="off"></el-input>
				</el-form-item>

			</el-form>

			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="handleLogin">登 录</el-button>
				</div>
			</template>
		</el-card>
	</div>
</template>

<script setup name='Login'>
	import QS from 'qs';
	import {
		ref,
		getCurrentInstance,
		nextTick
	} from 'vue';
	import {
		ElMessage
	} from 'element-plus';
	import {
		useAuthStore
	} from '@/stores/auth';
	const authStore = useAuthStore();
	const loginForm = ref({
		username: '',
		password: '',
	});
	import {
		useRouter
	} from 'vue-router';
	const router = useRouter();
	const {
		proxy
	} = getCurrentInstance()
	const loginRules = {
		username: [{
			required: true,
			message: '请输入用户名',
			trigger: 'blur'
		}, ],
		password: [{
			required: true,
			message: '请输入密码',
			trigger: 'blur'
		}, ],
	};

	const loginFormRef = ref(null);

	const handleLogin = () => {
		loginFormRef.value.validate(async (valid) => {
			if (!valid) {
				ElMessage.error('请检查输入信息')
				return
			}

			try {
				const config = {
					headers: {
						'Content-Type': 'application/x-www-form-urlencoded'
					}
				}

				const res = await proxy.$request.login(QS.stringify(loginForm.value), config)
				console.log('登录响应:', res)

				if (res.data.code !== 200 || !res.data.token) {
					ElMessage.error(res.data.message || '登录失败')
					return
				}

				// 使用 authStore 管理认证状态

				const authStore = useAuthStore()
				authStore.setToken(res.data.token)

				// 获取用户信息并存储
				const userInfoRes = await proxy.$request.getUserInfo()

				if (userInfoRes.data.code === 200 && userInfoRes.data.result) {
					await authStore.setAuth(
						res.data.token,
						userInfoRes.data.result.superAdmin ? 3 : 1,
						userInfoRes.data.result // 确保传递完整用户信息
					)

					// 等待状态完全更新
					await nextTick()

					// 直接跳转无需延迟
					router.push('/index')
					if (!proxy.$WS.connected) {
						proxy.$WS.tryReconnect()
					}

					ElMessage.success('登录成功')
				} else {
					ElMessage.error(res.data.message || '获取用户信息失败')
					return
				}

				// 	if (userInfoRes.data.code !== 200 ) {
				// 	  ElMessage.error(res.data.message || '获取用户信息失败')
				// 	  return
				// 	}



				// 	await authStore.setAuth(res.data.token, userInfoRes.data.result.superAdmin?3:1, userInfoRes.data.result)


				//      // const role =  3 // 默认角色3
				//      // authStore.setRole(role)

				//      // 跳转前确保状态更新
				//      await nextTick()

				// 	  // 路由跳转
				// 	  router.push('/index')



				// WebSocket 重连



			} catch (err) {
				console.error('登录错误:', err)
				ElMessage.error(err.data.message || '请求异常')
			}
		})
	}
</script>

<style scoped>
	.login-page {
		/* background: url("../../assets/login.png"); */
		/* background-size: cover; */
		/* 使背景图片自适应容器大小 */
		/* background-position: center; */
		/* 使背景图片居中显示 */
		/* background-repeat: no-repeat; */
		/* 防止背景图片重复 */
		background-image: linear-gradient(to right, #fbc2eb, #a6c1ee);
		/* 如果需要平铺背景图，则使用以下样式 */
		/* background-repeat: repeat; */
		/* 自适应屏幕大小 */
		display: flex;
		justify-content: center;
		align-items: center;
		height: 100vh;
		weight: 100%;
	}

	.login-card {
		width: 400px;
		/* 卡片宽度，可根据需要调整 */
		padding: 20px;
		border-radius: 8px;
		background-color: aliceblue;
		text-align: center;
		box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
	}

	.dialog-footer {
		display: flex;
		flex-direction: row-reverse;
	}
</style>